package com.lazason.wib4android;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.widget.TextView;

public class Welcome extends BasicActivity {
	/** Called when the activity is first created. */
	static final String WIB = "com.lazason.wib";
	Weibo weibo;
	static final String tag ="Welcome";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        Intent intent = this.getIntent();
        int flag = intent.getFlags();
		Log.d("Welcome", String.valueOf(flag));
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(WIB, mode);
		String token = mySharedPreferences.getString("token", null);
		String tokenSecret = mySharedPreferences.getString("tokenSecret", null);
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret",Weibo.CONSUMER_SECRET);
		//如果曾经登录过，直接使用保存在SharedPreferences中的token和tokenSecret登录
		if (token != null && tokenSecret != null) {
			setContentView(R.layout.welcome);
			TextView textView = (TextView) findViewById(R.id.welcometext);
			Animation animation = new AlphaAnimation(255,100);
			textView.setAnimation(animation);
			weibo = OAuthConstant.getInstance().getWeibo();
			weibo.setToken(token, tokenSecret);
			FirstTimeLineTask ftlt = new FirstTimeLineTask();
			ftlt.execute();
	  
	
			 //如果是第一次登录，打开授权页面
		}else{
			if(flag==Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT){
				//用于注销功能
				OAuthConstant.reset();
			}
			
			Weibo weibo = OAuthConstant.getInstance().getWeibo();
			if(flag==Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT){
				//weibo.setToken(null, null);
			}
			
			RequestToken requestToken;
			 
			try {
				
				//requestToken = weibo.getOAuthRequestToken("wibo4andriod://Wib");
				requestToken = weibo.getOAuthRequestToken("weibo4andriod://OAuthActivity");
				OAuthConstant.getInstance().setRequestToken(requestToken);
				WebView webview = new WebView(this);
				setContentView(webview);
				webview.getSettings().setJavaScriptEnabled(true);
				webview.getSettings().setSupportZoom(true);
				webview.getSettings().setBuiltInZoomControls(true);
				webview.loadUrl(requestToken.getAuthenticationURL()
						+ "&from=xweibo");
				
				
				 URL url;
				 
					url = new URL(requestToken.getAuthenticationURL()
								+ "&from=xweibo");
					 HttpURLConnection conn=(HttpURLConnection)url.openConnection();  
				        conn.setConnectTimeout(6*1000);  //设置链接超时时间6s  
				  
				        conn.setRequestMethod("GET");  
				  
				        if(conn.getResponseCode()==200)  
				        {  
				            InputStream inputStream=conn.getInputStream();  
				            byte[] data=readStream(inputStream);  
				            Log.d(tag, new String(data));  
				        }  
				        MyApplication.authFlag = true;
						System.out.println("url : " + requestToken.getAuthenticationURL()
								+ "&from=xweibo");
						//finish();

				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  catch (WeiboException e) {
				TextView textView = new TextView(this);
				textView.setText("程序出错");
				setContentView(textView);
				Log.d("Welcome", e.getMessage());
				try {
					Thread.sleep(1000);
					MyApplication.getInstance().exit();
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				 

			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  

		}
	}

	private class FirstTimeLineTask extends
			AsyncTask<Void, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Void... arg) {
			List<weibo4andriod.Status> friendsTimeline = null;
			
			try {

				friendsTimeline = weibo.getFriendsTimeline();

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}
			
			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			MyApplication.data = new ArrayList<Map<String, Object>>();
			 
			
			for (weibo4andriod.Status status : friendsTimeline) {
				Log.d("WIB", status.toString());
				Map<String, Object> map = Util.status2Map(status);
				
//				Map<String, Object> map = new HashMap<String, Object>();
//
//				map.put("profile", status.getUser().getProfileImageURL()
//						.toString());
//				map.put("weibo", status.getText());
//				map.put("username", status.getUser().getName());
//				map.put("id", status.getUser().getId());
				MyApplication.data.add(map);
				if(status.getInReplyToStatusId()>0){
					
				}

			}
			Intent intent = new Intent();
			intent.setClass(Welcome.this, TimelineActivity.class);
			startActivity(intent);
			//finish();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//MyApplication.getInstance().removeActivity(this);
		
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		
		super.onBackPressed();
		//MyApplication.getInstance().exit();
		
	}
	
	 public static byte[] readStream(InputStream inputStream) throws Exception  
	    {  
	        byte[] buffer=new byte[1024];  
	        int len=-1;  
	        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();  
	          
	        while((len=inputStream.read(buffer))!=-1)  
	        {  
	            byteArrayOutputStream.write(buffer,0,len);  
	        }  
	          
	        inputStream.close();  
	        byteArrayOutputStream.close();  
	        return byteArrayOutputStream.toByteArray();  
	    }  
	      
}